/**
 * 
 */
package org.libermundi.theorcs.chronicles.tapestry.pages.message;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.libermundi.theorcs.chronicles.dto.ChronicleSettings;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.chronicles.model.message.Channel;
import org.libermundi.theorcs.chronicles.model.message.TargetRole;
import org.libermundi.theorcs.chronicles.model.message.impl.InternalEmail;
import org.libermundi.theorcs.chronicles.model.message.impl.InternalEmailTarget;
import org.libermundi.theorcs.chronicles.services.AddressBookManager;
import org.libermundi.theorcs.chronicles.services.message.MessageChainService;
import org.libermundi.theorcs.chronicles.tapestry.base.ChroniclePage;
import org.libermundi.theorcs.core.tapestry.services.MultipleValueEncoderFactory;
import org.libermundi.theorcs.core.tapestry.util.GenericSelectModel;
import org.libermundi.theorcs.core.tapestry.util.MultipleValueEncoder;

import com.google.common.collect.Maps;

/**
 * @author sguichard
 * @author Martin Papy
 *
 */
public class Message extends ChroniclePage {
	
	public static final String PAGE_ID = "chronicles.pages.mail.write";

	/* (non-Javadoc)
	 * @see org.libermundi.theorcs.core.tapestry.BasePage#getPageId()
	 */
	@Override
	public String getPageId() {
		return PAGE_ID;
	}
	
	/*------------- Services -------------*/
	@SessionState
	private ChronicleSettings _chronicleSettings;
    
	@Inject
	private MessageChainService<InternalEmail, Persona> _messageService;
	
	@Inject
	private MultipleValueEncoderFactory<Persona> _genericManagerFactory;

	@Inject
	private AddressBookManager _addressBookManager;
	
	@Persist
	private Map<String, String> _mappedContacts;
	
	@Persist
	private List<Persona> _contacts;
	
	/*------------- Fields -------------*/
	@Property
	private Persona _sender;
	
	@Property
	private List<Persona> _to;
	
	@Property
	private List<Persona> _cc;
	
	@Property
	private List<Persona> _bcc;
	
	@Property
	private String _message;
	
	@Property
	private String _subject;
	
	/*------------- Rendering Phase -------------*/
	/**
	 * Load the contacts of the persona
	 */
	@SetupRender
	public void setupRender(){
		// get all the contacts of the caster
		_contacts = _addressBookManager.loadAddressBook(_chronicleSettings.getPersona()).getContactsAsList();
		_mappedContacts = Maps.newHashMap();
		for(Persona contact : _contacts) {
			_mappedContacts.put(contact.getId().toString(), contact.getName());
		}
	}
	
	public MultipleValueEncoder<Persona> getMultipleValueEncoder() {
		return _genericManagerFactory.create(Persona.class);
	}
	
	public SelectModel getGenericModel() {
		return new GenericSelectModel<Persona,Long>(_contacts,Boolean.FALSE);
	}
	
	public void onActivate(Long messageId){
		if(messageId!=null){
			InternalEmail msg = null;
			// load the messages of the persona
			msg = _messageService.getEntityMessage(messageId.longValue());
			_subject = msg.getTitle();
			_message = msg.getBody();
			List<InternalEmailTarget> _toTarget = msg.getRecipient();
			if(_to==null)
				_to = new ArrayList<Persona>();
			if(_cc==null)
				_cc = new ArrayList<Persona>();
			if(_bcc==null)
				_bcc = new ArrayList<Persona>();
			
			for (InternalEmailTarget tr: _toTarget){
				if(tr.getRole()==TargetRole.TO){
					_to.add(tr.getPersona());
				} else if(tr.getRole()==TargetRole.CC){
					_cc.add(tr.getPersona());
				} else if(tr.getRole()==TargetRole.BCC){
					_bcc.add(tr.getPersona());
				} else if(tr.getRole()==TargetRole.BY){
					_sender = tr.getPersona();			
				}
			}
		}
		
	}
	
	/**
	 * Send the message
	 * @return the messageIndex page
	 */
	@OnEvent(value="success",component="postMessageForm")
	public Class<?> success(){
		_sender = _chronicleSettings.getPersona();
		//create the internalEmail
		//TODO Factory
		InternalEmail msg = new InternalEmail();
		msg.setBody(_message);
		msg.setTitle(_subject);
		List<InternalEmailTarget> _toTarget = new ArrayList<InternalEmailTarget>();
		_toTarget.add(new InternalEmailTarget(_sender, TargetRole.BY));
		for (Persona p: _to){
			InternalEmailTarget tgt = new InternalEmailTarget(p, TargetRole.TO);
			_toTarget.add(tgt);
		}
		for (Persona p: _cc){
			InternalEmailTarget tgt = new InternalEmailTarget(p, TargetRole.CC);
			_toTarget.add(tgt);
		}
		for (Persona p: _bcc){
			InternalEmailTarget tgt = new InternalEmailTarget(p, TargetRole.BCC);
			_toTarget.add(tgt);
		}
		
		msg.setRecipient(_toTarget);
		_messageService.process(msg, Channel.INT_EMAIL);
		return Box.class;
	}

}
